package org.binarylook.nio;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.nio.charset.CharsetEncoder;
import java.util.Iterator;
import java.util.Set;
import java.net.InetSocketAddress;
import java.util.Hashtable;

public class Trail extends Server {

    @Override
    public void Start() {

        try {

            Hashtable UserRoom      = new Hashtable();
            
            ServerSocketChannel ssc = ServerSocketChannel.open();
            InetSocketAddress isa   = new InetSocketAddress(Conf.Server, Conf.Port);
            ssc.socket().bind(isa);
            ssc.configureBlocking(false);
            Selector sel = Selector.open();
            SelectionKey serverkey = ssc.register(sel, SelectionKey.OP_ACCEPT);

            System.out.println("Server Started");

            while (true) {

                sel.select();
                Set keys = sel.selectedKeys();

                for (Iterator itr = keys.iterator(); itr.hasNext();) {

                    SelectionKey tempkey = (SelectionKey) itr.next();
                    itr.remove();

                    if (tempkey == serverkey) {

                        System.out.println("server key received");

                        if (tempkey.isAcceptable()) {
                            SocketChannel channel  = ssc.accept();
                            channel.configureBlocking(false);
                            SelectionKey clientkey = channel.register(sel, SelectionKey.OP_READ);

                            Spawn ObjSpawn = new Spawn(clientkey);
                            UserRoom.put(clientkey, ObjSpawn);

                        }

                    } else {

                        System.out.println("Input message key has been received..");
                        SocketChannel client    = (SocketChannel) tempkey.channel();
                        if (tempkey.isReadable()) {
                            Spawn mySpawn = (Spawn)UserRoom.get(tempkey);
                            mySpawn.ReceiveMessage();

                        } else {
                            System.out.println("not readable socket"+tempkey.toString());
                            continue;
                        }

                    }

                }
            }

        } catch (IOException e) {
        }


    }
}
